import React, { useState, useEffect, useMemo } from 'react';
import { SearchOutlined, EditOutlined, DeleteOutlined, PlusOutlined, FileExcelOutlined } from '@ant-design/icons';
import { Table, Button, Modal, Form, Input, TreeSelect, InputNumber, message, Card, Descriptions, Space, Popconfirm } from 'antd';
import * as XLSX from 'xlsx';

const { TextArea } = Input;
const mockProjects = [
    { id: 1, name: '项目A' },
    { id: 2, name: '项目B' },
    { id: 3, name: '项目C' },
];
const userMap = {
    1: '张三',
    2: '李四',
    3: '王五',
};
const SupplierTreeData =[
    {
        title: '供应商',
        key: 1,
        value: 1,
        children: [
            { title: '钢筋供应商', key: 2, value: 2 },
            {
                title: '水泥供应商',
                key: 3,
                value: 3,
                children: [
                    { title: '建筑水泥供应商', key: 6, value: 6 },
                    { title: '家用水泥供应商', key: 7, value: 7 },
                ],
            },
        ],
    },
    {
        title: '五金材料供应商',
        key: 8,
        value: 8,
        children: [
            { title: '螺丝供应商', key: 9, value: 9 },
            { title: '螺帽供应商', key: 10, value: 10 },
        ],
    }
];

const MaterialsTypeTreeData = [
    {
        title: '建设材料',
        key: 1,
        value: 1,
        children: [
            { title: '钢筋', key: 2, value: 2 },
            {
                title: '水泥',
                key: 3,
                value: 3,
                children: [
                    { title: '建筑水泥', key: 6, value: 6 },
                    { title: '家用水泥', key: 7, value: 7 },
                ],
            },
        ],
    },
    {
        title: '五金材料',
        key: 8,
        value: 8,
        children: [
            { title: '螺丝', key: 9, value: 9 },
            { title: '螺帽', key: 10, value: 10 },
        ],
    },
];
const  mockSupplier = [
    { id: 1, name: '供应商A',type:2 },
    { id: 2, name: '供应商B',type:3 },
    { id: 3, name: '供应商C',type:9 },
];
const mockMaterials = [
    {
        id: 1,
        name: '螺丝',
        project: 1,
        code: 'MAT001',
        specification: 'Φ20mm',
        supplier: 3,
        unit_price: 45.5,
        type: 9,
        expected_amount: 100,
        purchase_amount: 80,
        expected_cost: 4550,
        cost: 3640,
        purchaser: 1,
        unit: '个' ,  //字符串
        rate: 0.13,
        remark: '首批采购'
    }
    ]
const MaterialList = () => {
    const [materials, setMaterials] = useState([]);
    const [filteredMaterials, setFilteredMaterials] = useState([]);
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [isDetailModalVisible, setIsDetailModalVisible] = useState(false);
    const [isAddModalVisible, setIsAddModalVisible] = useState(false);
    const [currentMaterial, setCurrentMaterial] = useState(null);
    const [searchText, setSearchText] = useState('');
    const [form] = Form.useForm();
    const [addForm] = Form.useForm();
    const [filterType, setFilterType] = useState(null);
    const [filterProject, setFilterProject] = useState(null);

    useEffect(() => {
        setMaterials(mockMaterials);
        setFilteredMaterials(mockMaterials);
    }, []);

    // 修复：分类和供应商节点的 key / value 必须相同
    const generateSupplierTreeWithSuppliers = (nodes) => {
        return nodes.map(node => {
            const childrenFromCategories = node.children ? generateSupplierTreeWithSuppliers(node.children) : [];
            const suppliersUnder = mockSupplier
                .filter(s => s.type === node.key)
                .map(s => ({
                    title: s.name,
                    key: `supplier-${s.id}`,     // key 唯一
                    value: `supplier-${s.id}`,   // value 和 key 一样，避免警告
                    isLeaf: true
                }));
            return {
                ...node,
                key: `cat-${node.key}`,
                value: `cat-${node.key}`,       // 分类 key = value
                children: [...childrenFromCategories, ...suppliersUnder]
            };
        });
    };

    const supplierTreeWithSuppliers = useMemo(() => generateSupplierTreeWithSuppliers(SupplierTreeData), []);

    // 编辑模态打开时确保表单填充最新 currentMaterial（否则 initialValues 可能只在首次渲染生效）
    useEffect(() => {
        if (currentMaterial) {
            form.setFieldsValue({
                ...currentMaterial,
                supplier: currentMaterial.supplier ? `supplier-${currentMaterial.supplier}` : undefined, // 转换
            });
        }
    }, [currentMaterial, form]);

    // 工具函数：通过 key 查找名称
    const findTitleByKey = (data, key) => {
        for (let node of data) {
            if (node.key === key) return node.title;
            if (node.children) {
                const found = findTitleByKey(node.children, key);
                if (found) return found;
            }
        }
        return '';
    };
    // 工具函数：通过 ID 查找项目名称
    const findProjectName = (id) => {
        const project = mockProjects.find(p => p.id === id);
        return project ? project.name : '';
    };

    // 工具函数：通过 ID 查找供应商名称
    const findSupplierName = (id) => {
        const supplier = mockSupplier.find(s => s.id === id);
        return supplier ? supplier.name : '';
    };

    // 工具函数：通过 ID 查找采购人名称
    const findUserName = (id) => {
        return userMap[id] || '';
    };

    // 搜索和筛选
    const handleSearch = (value, type, project) => {
        setSearchText(value);
        setFilterType(type);
        setFilterProject(project);

        let filtered = materials;

        if (value) {
            filtered = filtered.filter(item =>
                item.name.toString().toLowerCase().includes(value.toLowerCase())
            );
        }
        if (type != null) {
            filtered = filtered.filter(item => item.type === type);
        }
        if (project != null) {
            filtered = filtered.filter(item => item.project === project);
        }

        setFilteredMaterials(filtered);
    };

    // 打开模态框
    const showAddModal = () => { addForm.resetFields(); setIsAddModalVisible(true); };
    const showEditModal = (material) => {
        setCurrentMaterial(material);
        form.setFieldsValue({
            ...material,
        });
        setIsModalVisible(true);
    };
    const showDetailModal = (material) => { setCurrentMaterial(material); setIsDetailModalVisible(true); };
    const formatValues = (values) => {
        return {
            ...values,
            supplier: values.supplier ? parseInt(values.supplier.replace("supplier-", ""), 10) : null, // 还原成数字id
        };
    };
    const handleAdd = () => {
        addForm.validateFields().then(values => {
            const formatted = formatValues(values);
            const newId = materials.length > 0 ? Math.max(...materials.map(m => m.id)) + 1 : 1;
            const newMaterial = { id: newId, ...formatted };
            const updated = [...materials, newMaterial];
            setMaterials(updated);
            setFilteredMaterials(updated);
            setIsAddModalVisible(false);
            message.success('材料添加成功');
        });
    };

    const handleSave = () => {
        form.validateFields().then(values => {
            const formatted = formatValues(values);
            const updated = materials.map(m =>
                m.id === currentMaterial.id ? { ...m, ...formatted } : m
            );
            setMaterials(updated);
            setFilteredMaterials(updated);
            setIsModalVisible(false);
            message.success('材料信息更新成功');
        });
    };

    // 删除
    const handleDelete = (id) => {
        const updated = materials.filter(m => m.id !== id);
        setMaterials(updated);
        setFilteredMaterials(updated);
        message.success('材料删除成功');
    };

    // 导出Excel
    const exportToExcel = () => {
        const worksheet = XLSX.utils.json_to_sheet(filteredMaterials.map(m => ({
            'ID': m.id,
            '材料名称': m.name,
            '项目': findProjectName(m.project),
            '物料编码': m.code,
            '规格': m.specification,
            '供应商': findSupplierName(m.supplier),
            '材料类型': findTitleByKey(MaterialsTypeTreeData, m.type),
            '预计数量': m.expected_amount,
            '采购数量': m.purchase_amount,
            '预计金额': m.expected_cost,
            '金额': m.cost,
            '采购人': findUserName(m.purchaser),
            '单位': m.unit,
            '税率': m.rate,
            '备注': m.remark
        })));
        const workbook = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(workbook, worksheet, "材料清单");
        const today = new Date();
        const dateStr = `${today.getFullYear()}${(today.getMonth()+1).toString().padStart(2,'0')}${today.getDate().toString().padStart(2,'0')}`;
        XLSX.writeFile(workbook, `材料清单_${dateStr}.xlsx`);
    };

    // 表格列
    const columns = [
        { title: 'ID', dataIndex: 'id', key: 'id' },
        { title: '材料名称', dataIndex: 'name', key: 'name', render: (text, record)=> <a onClick={()=>showDetailModal(record)}>{text}</a> },
        { title: '项目', dataIndex: 'project', key: 'project', render: findProjectName },
        { title: '物料编码', dataIndex: 'code', key: 'code' },
        { title: '规格', dataIndex: 'specification', key: 'specification' },
        { title: '供应商', dataIndex: 'supplier', key: 'supplier', render: findSupplierName },
        { title: '材料类型', dataIndex: 'type', key: 'type', render: (tid) => findTitleByKey(MaterialsTypeTreeData, tid) },
        { title: '单位', dataIndex: 'unit', key: 'unit' },
        {
            title: '操作',
            key: 'action',
            render: (_, record) => (
                <Space>
                    <Button icon={<EditOutlined />} onClick={()=>showEditModal(record)}>编辑</Button>
                    <Popconfirm title="确认删除吗?" onConfirm={()=>handleDelete(record.id)}>
                        <Button danger icon={<DeleteOutlined />}>删除</Button>
                    </Popconfirm>
                </Space>
            )
        }
    ];

    return (
        <div style={{padding:24}}>
            <Card
                title="材料清单管理"
                extra={
                    <Space>
                        <Input.Search
                            placeholder="搜索材料名称"
                            allowClear
                            enterButton={<SearchOutlined />}
                            value={searchText}
                            onChange={e=>handleSearch(e.target.value, filterType, filterProject)}
                            onSearch={val=>handleSearch(val, filterType, filterProject)}
                            style={{width:300}}
                        />
                        <TreeSelect
                            style={{width:200}}
                            treeData={MaterialsTypeTreeData}
                            placeholder="筛选材料类型"
                            allowClear
                            treeDefaultExpandAll
                            value={filterType}
                            onChange={val=>handleSearch(searchText, val, filterProject)}
                        />
                        <TreeSelect
                            style={{width:200}}
                            treeData={mockProjects.map(p=>({title:p.name,key:p.id,value:p.id}))}
                            placeholder="筛选项目"
                            allowClear
                            value={filterProject}
                            onChange={val=>handleSearch(searchText, filterType, val)}
                        />
                        <Button type="primary" icon={<PlusOutlined />} onClick={showAddModal}>新增材料</Button>
                        <Button type="default" icon={<FileExcelOutlined />} onClick={exportToExcel}>导出Excel</Button>
                    </Space>
                }
            >
                <Table columns={columns} dataSource={filteredMaterials} rowKey="id" bordered pagination={{pageSize:10}} />
            </Card>

            {/* 编辑模态框 */}
            <Modal
                title="编辑材料信息"
                open={isModalVisible}
                onOk={handleSave}
                onCancel={()=>setIsModalVisible(false)}
                width={800}
                destroyOnHidden={ true}
            >
                <Form form={form} layout="vertical" initialValues={currentMaterial}>
                    <Form.Item label="材料名称" name="name" rules={[{required:true,message:'请输入材料名称'}]}><Input /></Form.Item>
                    <Form.Item label="项目" name="project" rules={[{required:true,message:'请选择项目'}]}><TreeSelect treeData={mockProjects.map(p=>({title:p.name,key:p.id,value:p.id}))} /></Form.Item>
                    <Form.Item label="物料编码" name="code"><Input /></Form.Item>
                    <Form.Item label="规格" name="specification"><Input /></Form.Item>
                    <Form.Item
                        label="供应商"
                        name="supplier"
                        rules={[
                            { required: true, message: '请选择供应商' },
                            {
                                validator: (_, value) => {
                                    if (!value) return Promise.reject(new Error('请选择供应商'));
                                    // 检查是否是叶子节点
                                    if (!value.startsWith('supplier-')) {
                                        return Promise.reject(new Error('请选择具体供应商（叶子节点），不可选择分类'));
                                    }
                                    return Promise.resolve();
                                }
                            }
                        ]}
                    >
                        <TreeSelect
                            treeData={supplierTreeWithSuppliers}
                            placeholder="请选择供应商（只能选择叶子节点）"
                            allowClear
                            treeDefaultExpandAll
                        />
                    </Form.Item>
                    <Form.Item label="材料类型" name="type"><TreeSelect treeData={MaterialsTypeTreeData} /></Form.Item>
                    <Form.Item label="单位" name="unit"><Input /></Form.Item>
                    <Form.Item label="预计数量" name="expected_amount"><InputNumber style={{width:'100%'}} /></Form.Item>
                    <Form.Item label="采购数量" name="purchase_amount"><InputNumber style={{width:'100%'}} /></Form.Item>
                    <Form.Item label="预计金额" name="expected_cost"><InputNumber style={{width:'100%'}} /></Form.Item>
                    <Form.Item label="金额" name="cost"><InputNumber style={{width:'100%'}} /></Form.Item>
                    <Form.Item label="采购人" name="purchaser"><TreeSelect treeData={Object.entries(userMap).map(([k,v])=>({title:v,key:k,value:k}))} /></Form.Item>
                    <Form.Item label="税率" name="rate"><InputNumber style={{width:'100%'}} min={0} max={1} step={0.01} /></Form.Item>
                    <Form.Item label="备注" name="remark"><TextArea rows={3} /></Form.Item>
                </Form>
            </Modal>

            {/* 新增模态框 */}
            <Modal
                title="新增材料"
                open={isAddModalVisible}
                onOk={handleAdd}
                onCancel={()=>setIsAddModalVisible(false)}
                width={800}
                destroyOnHidden={ true}
            >
                <Form form={addForm} layout="vertical">
                    <Form.Item label="材料名称" name="name" rules={[{required:true,message:'请输入材料名称'}]}><Input /></Form.Item>
                    <Form.Item label="项目" name="project" rules={[{required:true,message:'请选择项目'}]}><TreeSelect treeData={mockProjects.map(p=>({title:p.name,key:p.id,value:p.id}))} /></Form.Item>
                    <Form.Item label="物料编码" name="code"><Input /></Form.Item>
                    <Form.Item label="规格" name="specification"><Input /></Form.Item>
                    <Form.Item
                        label="供应商"
                        name="supplier"
                        rules={[
                            { required: true, message: '请选择供应商' },
                            {
                                validator: (_, value) => {
                                    if (!value) return Promise.reject(new Error('请选择供应商'));
                                    // 检查是否是叶子节点
                                    if (!value.startsWith('supplier-')) {
                                        return Promise.reject(new Error('请选择具体供应商（叶子节点），不可选择分类'));
                                    }
                                    return Promise.resolve();
                                }
                            }
                        ]}
                    >
                        <TreeSelect
                            treeData={supplierTreeWithSuppliers}
                            placeholder="请选择供应商（只能选择叶子节点）"
                            allowClear
                            treeDefaultExpandAll
                        />
                    </Form.Item>
                    <Form.Item label="材料类型" name="type"><TreeSelect treeData={MaterialsTypeTreeData} /></Form.Item>
                    <Form.Item label="单位" name="unit"><Input /></Form.Item>
                    <Form.Item label="预计数量" name="expected_amount"><InputNumber style={{width:'100%'}} /></Form.Item>
                    <Form.Item label="采购数量" name="purchase_amount"><InputNumber style={{width:'100%'}} /></Form.Item>
                    <Form.Item label="预计金额" name="expected_cost"><InputNumber style={{width:'100%'}} /></Form.Item>
                    <Form.Item label="金额" name="cost"><InputNumber style={{width:'100%'}} /></Form.Item>
                    <Form.Item label="采购人" name="purchaser"><TreeSelect treeData={Object.entries(userMap).map(([k,v])=>({title:v,key:k,value:k}))} /></Form.Item>
                    <Form.Item label="税率" name="rate"><InputNumber style={{width:'100%'}} min={0} max={1} step={0.01} /></Form.Item>
                    <Form.Item label="备注" name="remark"><TextArea rows={3} /></Form.Item>
                </Form>
            </Modal>

            {/* 详情模态框 */}
            <Modal
                title="材料详情"
                open={isDetailModalVisible}
                onCancel={()=>setIsDetailModalVisible(false)}
                footer={[<Button key="edit" type="primary" onClick={()=>{setIsDetailModalVisible(false);showEditModal(currentMaterial);}}>编辑</Button>,<Button key="close" onClick={()=>setIsDetailModalVisible(false)}>关闭</Button>]}
                width={800}
            >
                {currentMaterial && (
                    <Descriptions bordered column={2}>
                        <Descriptions.Item label="ID">{currentMaterial.id}</Descriptions.Item>
                        <Descriptions.Item label="材料名称">{currentMaterial.name}</Descriptions.Item>
                        <Descriptions.Item label="项目">{findProjectName(currentMaterial.project)}</Descriptions.Item>
                        <Descriptions.Item label="物料编码">{currentMaterial.code}</Descriptions.Item>
                        <Descriptions.Item label="规格">{currentMaterial.specification}</Descriptions.Item>
                        <Descriptions.Item label="供应商">{findSupplierName(currentMaterial.supplier)}</Descriptions.Item>
                        <Descriptions.Item label="材料类型">{findTitleByKey(MaterialsTypeTreeData, currentMaterial.type)}</Descriptions.Item>
                        <Descriptions.Item label="单位">{currentMaterial.unit}</Descriptions.Item>
                        <Descriptions.Item label="预计数量">{currentMaterial.expected_amount}</Descriptions.Item>
                        <Descriptions.Item label="采购数量">{currentMaterial.purchase_amount}</Descriptions.Item>
                        <Descriptions.Item label="预计金额">{currentMaterial.expected_cost}</Descriptions.Item>
                        <Descriptions.Item label="金额">{currentMaterial.cost}</Descriptions.Item>
                        <Descriptions.Item label="采购人">{findUserName(currentMaterial.purchaser)}</Descriptions.Item>
                        <Descriptions.Item label="税率">{currentMaterial.rate}</Descriptions.Item>
                        <Descriptions.Item label="备注" span={2}>{currentMaterial.remark}</Descriptions.Item>
                    </Descriptions>
                )}
            </Modal>
        </div>
    );
};

export default MaterialList;
